import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, TouchableOpacity, PixelRatio,
	ActivityIndicator, FlatList, TextInput, Alert
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import ValidateDataUtil from '../../../utils/ValidateDataUtil';
import HTTP from '../../../utils/http';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';

const emptyPic = require('../../../imgs/global/dealtWithEmpty.png');
const defaultLogo = require('../../../imgs/customer/office.png');
const searchLeft = require('../../../imgs/customer/searchLeft.png');

let totalPage = 1;//总的页数

const scale = GLOBAL.SCALE;
const requestObj = {
	searchCode: "",
	pageSize: 10,
};

class SearchInput extends Component {
	constructor(props) {
		super(props);
		this.state = {
			centerVisibility: true,
			opacity: 0
		}
		this.keyWord = '';
	}

	componentDidMount () {
		// this.refs.searchInput.focus();
	}

	render () {
		const searchInput = TextInput;

		return (
			<View style={styles.searchView}>
				<Image source={searchLeft} style={styles.searchLeftIcon} />
				<TextInput
					ref={"searchInput"}
					style={styles.searchInput}
					underlineColorAndroid='transparent'
					maxLength={20}
					placeholder='搜索'
					placeholderTextColor='#979797'
					onChangeText={(txt) => {
						this.props.setKeyWord(txt);
						this.keyWord = txt;
						// this.props.doSearch();
						this.setState({ opacity: txt.length > 0 ? 1 : 0 })
					}}
					onBlur={() => {
						if (!this.keyWord.length) {
							this.setState({
								centerVisibility: true
							});
						}
					}}
					onFocus={() => {
						this.setState({
							centerVisibility: false
						});
					}}
					onSubmitEditing={() => {
						this.props.doSearch();
					}}
				/>
			</View>
		);
	}

}

export class EnterpriseSearchPage extends Component {

	constructor(props) {
		super(props);
		this.state = {
			loaded: false,
			emptyResult: false,
			dataSource: [],
			showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
		}
		this.sendData = {
			companyId: this.companyId
		}
		this._renderEnterprise = this._renderEnterprise.bind(this);
		this._setKeyWord = this._setKeyWord.bind(this);
		this._fetchCustomerAsync = this._fetchCustomerAsync.bind(this);
		this._doSearch = this._doSearch.bind(this);
	}

	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		const backIcon = require('../../../imgs/global/backGray.png');
		const backIconStyle = { width: 20 * scale, resizeMode: 'contain', marginLeft: 10 * scale }

		const { sendAddressObj } = params;

		return {
			headerLeft: <TouchableOpacity onPress={() => navigation.goBack()} activeOpacity={0.5}><Image source={backIcon} style={backIconStyle} /></TouchableOpacity>,
			headerTitle: <SearchInput setKeyWord={(txt) => { params.setKeyWord && params.setKeyWord(txt); }} doSearch={() => { params.doSearch(); }} />,
			headerTintColor: '#404040',
			headerRight: (
				<Text style={{ marginRight: 10 * scale, fontSize: 12 * scale, color: '#404040' }} onPress={() => { params.doSearch(); }}>搜索</Text>
			),
			headerBackTitleStyle: {
				fontSize: 12 * scale, color: '#404040'
			},
			headerStyle: {
				elevation: 0,
				borderBottomWidth: 1,
				borderBottomColor: '#E4E4E4',
				backgroundColor: '#fff',
			},
		};
	};

	/**
	 * 设置搜索关键字
	 * @param {String} txt 
	 */
	_setKeyWord (txt) {
		requestObj.searchCode = txt;
	}

	componentWillMount () {
	}

	async componentDidMount () {
		requestObj.searchCode = '';
		this.props.navigation.setParams({
			doSearch: this._doSearch,
			setKeyWord: this._setKeyWord
		});
	}

	/**
	 * 
	 */
	async _doSearch () {
		if (requestObj.searchCode && requestObj.searchCode.length) {
			this.setState({
				loaded: true,
				dataSource: [],
				emptyResult: false,
			});
			this._fetchCustomerAsync(1, this.props.navigation.state.params.listType);
		} else {
			Alert.alert('请填写搜索条件');
		}

	}
	/**
 * @private
 */
	async _fetchCustomerAsync (pageNo, type) {
		requestObj.pageNo = pageNo;

		if (type === '我的客户') {
			requestObj.isEdit = null;
			responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_LIST), requestObj);
		} else if (type === '草稿') {
			requestObj.isEdit = '1';  //查草稿
			responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_APPLY_LIST), requestObj);
		} else if (type === '审核') {  //查审核 默认不传status
			requestObj.isEdit = '2';
			responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_APPLY_LIST), requestObj);
		}

		let newCustomers = [];

		if (!responseData) {

			this.setState({
				loaded: false,
			});

		} else {
			let emptyResult = false;
			if (responseData.rows) {
				newCustomers = responseData.rows;
				emptyResult = (!responseData.rows.length) ? true : false;
			}

			if (responseData.totalPage) {
				totalPage = responseData.totalPage;
			}
			let foot = 0;
			if (pageNo >= totalPage) {
				foot = 1;//listView底部显示没有更多数据了
			}

			this.setState({
				dataSource: pageNo == 1 ? newCustomers : this.state.dataSource.concat(newCustomers),
				loaded: false,
				showFoot: foot,
				emptyResult: emptyResult,
			});
		}
	}

	render () {

		if (this.state.loaded) {
			//数据加载未完成
			return this.renderLoadingView();
		} else {

			const emptyResult = this.state.emptyResult ?
				<View style={styles.panelEmptyView}>
					<Image source={emptyPic} style={styles.emptyPic} />
					<Text style={styles.emptyText}>没有查询到满足条件的客户</Text>
				</View> : <Text style={styles.resultTitle}>搜索结果</Text>;

			// const resultTitle = this.state.emptyResult ? null : <Text style={styles.resultTitle}>搜索结果</Text>;
			return (
				<View style={{ flex: 1, backgroundColor: '#fff' }}>

					{emptyResult}
					<FlatList data={this.state.dataSource}
						renderItem={this._renderEnterprise}
						style={styles.listView}>
					</FlatList>
				</View>
			);
		}
	}

	//加载等待页
	renderLoadingView () {
		return (
			<View style={styles.container}>
				<View style={styles.loadedCell}>
					<ActivityIndicator
						animating={true}
						color={'#fff'}
						size="small"
					/></View>
			</View>
		);
	}

	_renderEnterprise (enterprise) {

		const {
			id,
			companyId,
			companyName,
			dictName,
			createTime,
			creditLimit,
			logo,
			companyTypeName,
			corpTypeName
		} = enterprise.item;

		const limitView = (!ValidateDataUtil.isEmpty(creditLimit) && creditLimit > 0) ? <View style={styles.limitView}>
			<Text style={styles.limitText}>信</Text>
		</View> : null;
		const companyTypeText = companyTypeName ? <View style={styles.explainCell}>
			<Text style={styles.explainText} numberOfLines={1}>{companyTypeName}</Text>
		</View> : null;
		let corpTypeText = corpTypeName ? <View style={styles.explainCell}>
			<Text style={styles.explainText} numberOfLines={1}>{corpTypeName}</Text>
		</View> : null;

		const classificationImg = (ValidateDataUtil.isEmpty(logo)) ? defaultLogo : { uri: logo };
		const _getDateStr = str => {
			if (!str) {
				return '';
			} else {
				const currDate = new Date(str.replace(/-/g, '/'));
				var y = currDate.getFullYear(),
					m = currDate.getMonth() + 1,
					d = currDate.getDate();
				let dateStr = "";
				dateStr += y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
				return dateStr;
			}
		}
		return (
			<TouchableOpacity activeOpacity={0.5} style={styles.customerRow} onPress={() => {
				const { navigate } = this.props.navigation;
				const goPage = (this.props.navigation.state.params.listType === '草稿') ? 'EnterpriseCreateBaseInfo' : 'EnterpriseDetailsPage';
				navigate(goPage, {
					companyId: companyId,
					id: id,
					title: companyName,
					status: this.props.navigation.state.params.listType === '我的客户' ? 'PASS' : 'UNPASS',
				});
			}}>
				<View style={styles.classificationView}>
					<Image source={classificationImg} style={styles.classificationImg} />
				</View>
				<View style={styles.infoView}>
					<View style={{ flexDirection: 'row', }}>
						<Text style={styles.customerNameText}>{companyName}</Text>{limitView}
					</View>
					<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
						{companyTypeText}
						{corpTypeText}
					</View>
				</View>

			</TouchableOpacity >
		);
	}

}

const styles = StyleSheet.create({
	resultTitle: {
		fontSize: 12 * scale,
		color: '#404040',
		marginTop: 9 * scale,
		marginLeft: 14 * scale,
	},
	panelEmptyView: {
		height: 375 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		width: 375 * scale,
	},
	emptyPic: {
		width: 143 * scale,
		height: 120 * scale,
	},
	emptyText: {
		marginTop: 16 * scale,
		marginBottom: 60 * scale,
		fontSize: 13 * scale,
		color: '#4B4B4B'
	},
	searchView: {
		paddingLeft: 5 * scale,
		alignItems: 'center',
		flex: 1,
		flexDirection: 'row',
		width: 300 * scale,
		height: 31 * scale,
		backgroundColor: '#F6F6F6',
		borderRadius: 4,
	},
	searchInput: {
		padding: 0,
		flex: 1,
		height: 31 * scale,
		fontSize: 12 * scale,
		color: '#979797',
		marginLeft: 3 * scale,
	},
	searchLeftIcon: {
		height: 13 * scale,
		width: 13 * scale,
		marginLeft: 10 * scale,
		marginRight: 10 * scale,
	},
	searchRightIcon: {
		height: 10 * scale,
		width: 10 * scale,
		marginRight: 10 * scale,
	},
	container: {
		flex: 1,
		backgroundColor: '#fff',
		justifyContent: 'center',
		alignItems: 'center',
	},
	limitView: {
		width: 18 * scale,
		height: 13 * scale,
		marginLeft: 4 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: style.color.themeColor,
	},
	limitText: {
		fontSize: 10 * scale,
		color: '#fff'
	},
	listView: {
		backgroundColor: '#fff',
	},
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
	},
	customerRow: {
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		width: 375 * scale,
		paddingTop: 12 * scale,
		paddingBottom: 16 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 14 * scale,
		flexDirection: 'row'
	},
	classificationView: {
		flex: 1,
		justifyContent: 'center',
	},
	classificationImg: {
		width: 44 * scale,
		height: 44 * scale,
		resizeMode: 'contain'
	},
	infoView: {
		flex: 4,
		justifyContent: 'space-between',
	},
	dateView: {
		flex: 2,
		alignItems: 'flex-end',
	},
	customerNameText: {
		fontSize: 14 * scale,
		color: '#4B4B4B',
	},
	explainText: {
		fontSize: 12 * scale,
		color: '#8B8B8B',
	},
	explainCell: {
		paddingLeft: 5 * scale,
		paddingRight: 5 * scale,
		marginTop: 5 * scale,
		justifyContent: 'center',
		height: 20 * scale,
		borderBottomColor: '#e9e9e9',
		borderBottomWidth: 1 / PixelRatio.get(),
		backgroundColor: '#f4f4f4',
		marginRight: 6 * scale,
		borderRadius: 3,
	},
	explainText: {
		fontSize: 12 * scale,
		color: '#8B8B8B',
	},
})